import os
import random

from config.logger_config import logger
# from gevent import monkey

# monkey.patch_all()  # 必须放到被打补丁者（如time，socket模块）的前面

import time
from flask import Flask
import gevent


app = Flask(__name__)
global_variable = random.randint(1,  1000)
def gf(name):
    logger.debug(f"gf {name} {time.time()}")
    gevent.sleep(2)  # 这里用gevent的sleep代替耗时操作，也可以是实际的网络等待、文件读写等耗时操作
    return f"Hello, {name}!"

@app.route('/get-sync', methods=['GET'])
def hello2():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"global_variable:{global_variable}, sync api {time.time()} by worker PID:{worker_pid}")
    gf('张三')
    gf('李三')
    return f'Hello2, World! {time.time()}'

@app.route('/get-async', methods=['GET'])
def hello():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"global_variable:{global_variable}, async api {time.time()} by worker PID:{worker_pid}")
    greenlet = gevent.spawn(gf, '张三')
    greenleto = gevent.spawn(gf, '李三')
    greenlet.join()
    greenleto.join()
    logger.debug(f"get info {greenlet.value} at {time.time()}")
    logger.debug(f"get info {greenleto.value} at {time.time()}")
    return f'finished at {time.time()}!'

#gunicorn通过配置启动： gunicorn -c gunicorn_config_4_flask_gevent_web.py flask_gevent_web:app
if __name__ == '__main__':
    # app.run(host='0.0.0.0', port=5600)
    from gevent.pywsgi import WSGIServer

    http_server = WSGIServer(("127.0.0.1", 5600), app)
    http_server.serve_forever()